package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.atguigu.lease.common.minio.MinioProperties;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // Make bucket if not exist.
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());

        if (!found) {
            // Make a new bucket called
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
        } else {
            System.out.println("Bucket already exists.");
        }

        //设置访问权限
        String policyJson = """
                {
                    "Version": "2012-10-17",
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": {
                                "AWS": [
                                    "*"
                                ]
                            },
                            "Action": [
                                "s3:GetObject"
                            ],
                            "Resource": [
                                "arn:aws:s3:::%s/*"
                            ]
                        }
                    ]
                }
                """.formatted(minioProperties.getBucketName());
        //formatted的作用是代替%s，将minioProperties.getBucketName()替换为%s

        //设置权限
        minioClient.setBucketPolicy(
                SetBucketPolicyArgs
                        .builder()
                        .bucket(minioProperties.getBucketName())
                        .config(policyJson)
                        .build()
        );

        //获取文件名字
        //文件路径，防止根路径下文件过多影响查找效率，策略是以每一天的日期作为路径
        String filepath = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //加上uuid，防止文件重名覆盖
        String filename = UUID.randomUUID() + "-" + file.getOriginalFilename();

        //上传文件
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        //文件上传路径
                        .object(filepath + "/" + filename)//文件路径+文件名
                        //文件流
                        .stream(file.getInputStream(), file.getSize(), -1)
                        //文件类型
                        .contentType(file.getContentType())
                        .build());

        //最后我们要返回这个文件的url地址
//        return "http://192.168.6.200:9000/dongdong/test/%E6%88%BF%E9%97%B4-%E5%8E%A8%E6%88%BF-1.jpg";
        //使用String中的join方法，代替连续的+操作符
        return String.join(
                "/",
                minioProperties.getEndpoint(),
                minioProperties.getBucketName(),
                filepath,
                filename
        );
    }
}
